<template>
  <div>
    <div class="header">人员异动申请表</div>
    <el-form
      ref="transPositionForm"
      v-loading="loading"
      :model="transPositionForm"
      label-width="0px"
    >
      <table class="entryTable" cellspacing="0" cellpadding="0">
        <tr class="firstTr">
          <td width="20%" class="firstTd title required">姓名</td>
          <td width="40%" colspan="2">
            <el-form-item prop="name">
              <el-select v-model="transPositionForm.name" value-key="id" filterable no-data-text="无员工数据"
                         placeholder="请选择员工" style="width:100%" @change="changeUser"
              >
                <el-option value="" label="请选择员工"/>
                <el-option v-for="(item,index) in regularUserList" :key="index" :value="item" :label="item.name"/>
              </el-select>
            </el-form-item>
          </td>
          <td width="20%" class="title">入职时间</td>
          <td width="20%">
            <el-form-item prop="entryDate">
              {{ transPositionForm.comp_fill_entry_date|formatDate }}
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td width="20%"
              :rowspan="[transPositionForm.old_dept_list != null?transPositionForm.old_dept_list.length+1:1]"
              class="title"
          >原部门职位
          </td>
          <td width="20%" class="title">部门</td>
          <td width="20%" class="title">职位</td>
          <td width="20%" class="title">主部门</td>
          <td width="20%" class="title">负责人</td>
        </tr>
        <tr v-for="(item) in transPositionForm.old_dept_list">
          <td>{{ item.department }}</td>
          <td>{{ item.job }}</td>
          <td>{{ item.main ? '是' : '否' }}</td>
          <td>{{ item.business_head ? '是' : '否' }}</td>
        </tr>
        <tr>
          <td class="firstTd title required">调岗原因</td>
          <td colspan="4" class="textarea-wrapper">
            <el-input v-model="transPositionForm.reason"
                      type="textarea" clearable :rows="4" placeholder="请输入调岗原因" maxlength="200" resize="none"
                      show-word-limit
            />
          </td>
        </tr>
        <tr>
          <td class="firstTd title required">原调岗职责</td>
          <td colspan="4" class="textarea-wrapper">
            <el-input v-model="transPositionForm.old_job_duty"
                      type="textarea" clearable :rows="4" placeholder="请输入原调岗职责" maxlength="200" resize="none"
                      show-word-limit
            />
          </td>
        </tr>
        <tr>
          <td
            :rowspan="[transPositionForm.new_dept_list != null?transPositionForm.new_dept_list.length+1:1]"
            class="title required"
          >现部门职位
          </td>
          <td class="title">部门</td>
          <td class="title">职位</td>
          <td class="title">主部门</td>
          <td class="title">负责人</td>
          <i
            v-show="(transPositionForm.flow_status == null || transPositionForm.flow_status ==0 || transPositionForm.flow_status==2) && (transPositionForm.work_experiences == null || transPositionForm.work_experiences.length<5)"
            class="el-icon-circle-plus-outline"
            style="position:absolute;margin-left:10px;margin-top:20px;font-size:25px;color:rgb(64, 158, 255)"
            @click="postListAdd()"
          />
        </tr>
        <tr v-for="(item,index) in transPositionForm.new_dept_list">
          <td>
            <el-form-item>
              <TreeSelect
                ref="depTreeSelect"
                v-model="item.id"
                :data="departmentList"
                :height="400"
                :popover-width="300"
                default-expand-all
                :default-props="{
                  children: 'children',
                  label: 'name',
                }"
                node-key="id"
                @change="deptChange(arguments,item)"
              />
            </el-form-item>
          </td>
          <td>
            <el-form-item>
              <el-input v-model="item.job" placeholder="请输入职位"/>
            </el-form-item>
          </td>
          <td>
            <el-form-item>
              <el-radio
                v-model="mainPostIdIndex"
                :label="index"
                @click.native.prevent="changeMainPost(index)"
              >{{ '' }}
              </el-radio>
            </el-form-item>
          </td>
          <td>
            <el-form-item>
              <el-checkbox v-model="item.business_head" label="true">{{ '' }}</el-checkbox>
            </el-form-item>
          </td>
          <i
            v-show="transPositionForm.flow_status == null|| transPositionForm.flow_status==0 || transPositionForm.flow_status==2"
            class="el-icon-remove-outline"
            style="position:absolute;margin-left:10px;margin-top:20px;font-size:25px;color:red;"
            @click="postListRemove(index)"
          />
        </tr>
        <tr>
          <td class="firstTd title required">现调岗职责</td>
          <td colspan="4" class="textarea-wrapper">
            <el-input v-model="transPositionForm.new_job_duty"
                      type="textarea" clearable :rows="4" placeholder="请输入现调岗职责" maxlength="200" resize="none"
                      show-word-limit
            />
          </td>
        </tr>
        <tr>
          <td class="firstTd title required" rowspan="3">是否调薪</td>
          <td rowspan="2">
            <el-radio v-model="transPositionForm.change_salary" :label="true">是</el-radio>
          </td>
          <td class="title">调整前薪资</td>
          <td colspan="2">
            <el-form-item prop="comp_fill_salary">
              <el-input v-model="transPositionForm.before_change_salary" placeholder="请输入调整前薪资">
                <template slot="prepend">&yen;</template>
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td class="title">调整后薪资</td>
          <td colspan="3">
            <el-form-item prop="comp_fill_salary">
              <el-input v-model="transPositionForm.after_change_salary" placeholder="请输入调整后薪资">
                <template slot="prepend">&yen;</template>
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td width="90%" colspan="4">
            <el-radio v-model="transPositionForm.change_salary" :label="false">否</el-radio>
          </td>
        </tr>
        <tr>
          <td class="firstTd title required">生效时间</td>
          <td colspan="4">
            <el-form-item prop="contract_sign_at">
              <el-date-picker
                v-model="transPositionForm.effect_date"
                type="date"
                placeholder="选择合同签订时间"
                style="width:100%"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </td>
        </tr>
      </table>
    </el-form>

    <div style="text-align: center;margin-bottom: 30px">
      <FlowBtnRow :flow-status="transPositionForm.flow_status" :can-check="transPositionForm.can_check"
                  :is-applyer="transPositionForm.is_applyer" :is-new-data="transPositionForm.isNewData"
                  @save="onSave" @submit="onSubmit" @returnBack="onReturnBack" @pass="onPass" @delete="onDelete"
                  @actualDelete="onActualDelete" :flowType="9"
                  :dataId="(params || {}).id || ((params || {}).handle_param || {}).id"
      />
    </div>

  </div>
</template>

<script>
import {
  actualDeleteData,
  deleteData,
  getDetail2 as getTransPositionDetails,
  pass as passData,
  returnBack as returnBackData,
  save as saveData,
  saveAndBegin
} from '@/api/personnel/trans_position'
import { list_regular_user } from '@/api/personnel/org/roster'
import { formatDateByFmt } from '@/utils/util'
import { list as getDepartmentList } from '@/api/system/department'
import { Message } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
import FlowBtnRow from '@/components/FlowBtnRow'

export default {
  name: 'TransPosition',
  components: {
    TreeSelect,
    FlowBtnRow
  },
  filters: {
    formatDate(time) {
      if (time) {
        return formatDateByFmt(time, 'yyyy年MM月dd日')
      }
    }
  },
  data() {
    return {
      roster_id: null,
      loading: false,
      departmentList: [],
      regularUserList: [],
      mainPostIdIndex: 0,
      transPositionForm: {
        flow_status: 0,
        can_check: false,
        is_applyer: true,
        isNewData: true,
        name: null,
        roster_id: null,
        comp_fill_entry_date: null,
        old_dept_list: [],
        reason: null,
        old_job_duty: null,
        new_dept_list: [],
        after_change_salary: null,
        before_change_salary: null,
        change_salary: true,
        effect_date: null,
        new_job_duty: null
      },
      params: {}
    }
  },
  mounted() {
    // if (this.$route.params.id || (this.$route.params.handle_param && this.$route.params.handle_param.id)) {
    //   this.getDetails(this.$route.params.id || this.$route.params.handle_param.id)
    // }
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    this.params = params
    if (!!params.handle_param && !!params.handle_param.id) {
      this.getDetails({ id: params.handle_param.id })
    } else {
      if (!!params.roster_id) this.roster_id = params.roster_id
      this.getDetails({
        id: !!params.id ? params.id : null,
        roster_id: params.roster_id
      })
    }
    this.getDepartmentList()
    this.getRegularUserList()
  },
  methods: {
    changeUser(user) {
      this.transPositionForm.name = user.name
      this.transPositionForm.roster_id = user.id
      this.transPositionForm.comp_fill_entry_date = user.comp_fill_entry_date
      this.transPositionForm.old_dept_list.length = 0
      for (let i = 0; i < user.department_list.length; i++) {
        const dept = user.department_list[i]
        this.transPositionForm.old_dept_list.push({
          id: dept.id,
          business_head: dept.business_head,
          department: dept.name,
          job: dept.job,
          main: dept.main
        })
      }
    },
    deptChange(args, item) {
      let names = []
      let node = args[1]
      do {
        if (node.data.name) {
          names.push(node.data.name)
        }
        node = node.parent
      } while (node)
      names = names.reverse()
      item.department = names.join('/')
    },
    getRegularUserList() {
      return list_regular_user().then(res => {
        this.regularUserList = res.data
        if (!!this.roster_id) {
          // 由花名册跳转过来的
          let user = null
          for (let i = 0; i < (this.regularUserList || []).length; i++) {
            if (parseInt(this.regularUserList[i].id) == parseInt(this.roster_id)) {
              user = this.regularUserList[i]
              break
            }
          }
          if (!!user) {
            this.changeUser(user)
          }
        }
      })
    },
    postListAdd() {
      if (this.transPositionForm.new_dept_list.length > 4) {
        return
      }
      this.transPositionForm.new_dept_list.push({
        id: null,
        business_head: false,
        department: null,
        job: null,
        main: null
      })
    },
    postListRemove(index) {
      this.transPositionForm.new_dept_list.splice(index, 1)
    },
    changeMainPost(index) {
      this.mainPostIdIndex = index
    },
    getDetails({ id, roster_id }) {
      this.loading = true
      return getTransPositionDetails({ id, roster_id })
        .then(res => {
          if (res.data) {
            this.transPositionForm = Object.assign({}, this.transPositionForm, res.data)
            for (let i = 0; i < this.transPositionForm.new_dept_list.length; i++) {
              if (this.transPositionForm.new_dept_list[i].main) {
                this.mainPostIdIndex = i
              }
              this.$nextTick(() => {
                this.$refs['depTreeSelect'][i].checkSelectedNode([this.transPositionForm.new_dept_list[i].id])
              })
            }
            this.transPositionForm.isNewData = false
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取部门信息
    getDepartmentList() {
      return getDepartmentList().then(res => {
        this.departmentList = res.data
      })
    },
    // 保存
    onSave() {
      this.$refs.transPositionForm.validate(valid => {
        if (valid) {
          if (this.transPositionForm.change_salary && (!this.transPositionForm.before_change_salary || !this.transPositionForm.after_change_salary)) {
            const message = '请填写调前薪资和调后薪资!'
            Message({
              message,
              type: 'warning',
              duration: 1000
            })
            return false
          }
          this.transPositionForm.new_dept_list[this.mainPostIdIndex].main = true
          var obj = Object.assign({}, this.transPositionForm)
          // 显示loading
          this.loading = true
          delete obj.created_at

          this.save(obj)
        } else {
          // ~ 不通过
          return false
        }
      })
    },
    // 保存数据
    save(obj) {
      saveData(obj).then(res => {
        const {
          code,
          message
        } = res
        if (code === 200) {
          Message({
            message,
            type: 'success',
            duration: 1000
          })
          this.detail()
        }
        this.loading = false
      })
        .catch(() => {
          this.loading = false
        })
    },
    // 提交
    onSubmit() {
      // 表单校验
      this.$refs.transPositionForm.validate(valid => {
        if (valid) {
          if (this.transPositionForm.change_salary && (!this.transPositionForm.before_change_salary || !this.transPositionForm.after_change_salary)) {
            const message = '请填写调前薪资和调后薪资!'
            Message({
              message,
              type: 'warning',
              duration: 1000
            })
            return false
          }
          this.transPositionForm.new_dept_list[this.mainPostIdIndex].main = true
          var obj = Object.assign({}, this.transPositionForm)
          // 显示loading
          this.loading = true

          delete obj.created_at
          this.submit(obj)
        } else {
          return false
        }
      })
    },
    // 提交数据
    submit(obj) {
      saveAndBegin(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            // this.$router.go(-1)
            this.$store.dispatch('tagsView/closeCurPage')
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    onPass(opinion) {
      this.loading = true
      passData({ id: this.transPositionForm.id, wf_check_opinion: opinion })
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            // this.$router.go(-1)
            this.$store.dispatch('tagsView/closeCurPage')
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    onReturnBack(opinion) {
      this.loading = true
      returnBackData({ id: this.transPositionForm.id, wf_check_opinion: opinion })
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            // this.$router.go(-1)
            this.$store.dispatch('tagsView/closeCurPage')
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    onActualDelete() {
      this.loading = true
      actualDeleteData(this.transPositionForm.id)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            // this.$router.go(-1)
            this.$store.dispatch('tagsView/closeCurPage')
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    onDelete() {
      this.loading = true
      deleteData(this.transPositionForm.id)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            // this.$router.go(-1)
            this.$store.dispatch('tagsView/closeCurPage')
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped lang="scss">

.entryTable {
  width: 90%;
  font-size: 14px;
  margin: 0 auto 30px auto;
}

.entryTable tr td {
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.header {
  padding-top: 20px;
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 20px auto;
}

.tip {
  color: red;
}

.textarea-box {
  padding: 10px !important;
}

.follow_table {
  margin-top: 20px;
}

.button_group {
  margin: 20px auto;
  text-align: center;
}

.no_last {
  padding-top: 37px;
}

/deep/ .el-form-item {
  margin-bottom: 0;
}

.error_box {
  margin-bottom: 22px;
}

.button_box {
  text-align: center;
  margin-top: -10px;
  padding-bottom: 10px;
}

/deep/ .el-dialog__title {
  font-size: 14px;
}

.sign {
  float: right;
  width: 400px;
  text-align: left;
}

.departwrapper /deep/ .el-input__inner,
.postwrapper /deep/ .el-input__inner {
  border: none;
}

.departwrapper /deep/ .el-form-item__label,
.postwrapper /deep/ .el-form-item__label {
  margin-top: 3px;
  color: #000;
}

.required:before {
  content: "*";
  color: #F56C6C;
  margin-right: 4px;
}

.title {
  background: #F5F7FA;
  font-weight: bold;
}

.entryTable tr td.textarea-wrapper {
  padding: 10px 0 0 0;
}

.textarea-wrapper /deep/ .el-textarea textarea {
  border: 0;
}

///deep/ .el-input__inner{
//  border: none;
//}
</style>

